import { ossConfig } from 'libs/config'

// oss下载
// import { downloadByObjectKey } from 'libs/utils'
// downloadByObjectKey('zilong/pic/TEACH_MASTER/TM_571456_1556784117080/2019-05-02/1556784119115.zip')
export const downloadByObjectKey = objectKey => {
  const OSS = require('ali-oss');
  const client = new OSS(ossConfig);
  const url = client.signatureUrl(objectKey, {expires: 3600});
  window.open(url)
}

//cookie相关操作
export const cookie = {
  get: key => {
    let value = null;
    document.cookie.split('; ').forEach((item) => {
      const arr = item.split('=');
      if (arr[0] === key) {
        value = decodeURI(arr[1]);
      }
    });
    return value;
  },
  set: ({ key, value, expires, path }) => {
    document.cookie=`${key}=${value}; expires=${expires}; path=${path}`;
  },
  delete: key => {
    document.cookie=`${key}=; expires=Thu, 01 Jan 2000 00:00:00 GMT`;
  }
};

export const formatDate = (fmt, date2) => {
  if(!date2) {
    console.log('%c 时间格式不正确', 'color:red;', date2 )
    return ''
  };
  let date = new Date(date2);
  var o = {
      "M+" : date.getMonth()+1,                 //月份
      "D+" : date.getDate(),                    //日
      "h+" : date.getHours(),                   //小时
      "m+" : date.getMinutes(),                 //分
      "s+" : date.getSeconds(),                 //秒
      "q+" : Math.floor((date.getMonth()+3)/3), //季度
      "s"  : date.getMilliseconds()             //毫秒
  };
  if(/(y+)/i.test(fmt))
      fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
      if(new RegExp("("+ k +")").test(fmt))
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}

export const getWeek = (date, type) => {
  const weekNo = new Date(date).getDay()
  let week = ''
  type = type || '星期'
  switch(weekNo){
    case 1: week = type + '一'; break;
    case 2: week = type + '二'; break;
    case 3: week = type + '三'; break;
    case 4: week = type + '四'; break;
    case 5: week = type + '五'; break;
    case 6: week = type + '六'; break;
    case 0: week = type + '日'; break;
  }
  return week;
}

export const forMatSex = (code) => {
  if (code === 1) {
    return '男';
  } else if (code === 2) {
    return '女';
  } else {
    return '未知';
  }
}

export const transformDate = (second) => {
  let hour = Math.floor(second/3600);
  let mint = Math.floor(second % 3600 / 60);
  let secon = Math.floor(second % 3600 % 60);
  if (hour < 10) { hour = `0${hour}` };
  if (mint < 10) { mint = `0${mint}` };
  if (secon < 10) { secon = `0${secon}` };
  return `${hour}:${mint}:${secon}`;
}

// 普通弹框
export const _alert = (msg='模拟alert弹框') => {

  let alertEle = null
  let closeCallback
  const hash = new Date().getTime()

  init()

  function init() {
    createalertEle()
    document.addEventListener('click', resetTask, false)
    document.addEventListener('touchend', resetTask, false)
  }
  function createalertEle() {
    alertEle = document.createElement('div')
    alertEle.style.width = window.innerWidth + 'px'
    alertEle.style.height = window.innerHeight + 'px'
    alertEle.style.position = 'fixed'
    alertEle.style.left = 0
    alertEle.style.top = 0
    alertEle.style.zIndex = 999999999
    alertEle.style.backgroundColor = 'rgba(0,0,0,0.7)'
    alertEle.style.display = 'block'

    const alertStr = `
      <div style="width: 400px; height: 180px; background: #fff; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); font-size: 16px; border-radius: 5px; overflow: hidden;">
        <p style="width: 100%; height: 40px; line-height: 40px; font-weight: 700; background: #efefef; color: #333; text-indent: 28px; border-bottom: 1px solid #ccd0d6; margin: 0;">提示</p>
        <div style="text-align: center;">
          <p style="width: 100%; line-height: 80px; text-align: center; font-weight: 700; margin: 0;">${msg}</p>
          <button id=${'_alert_id_' + hash} style="width: 120px; height: 34px; line-height: 34px; background: rgb(41, 155, 228); color: #fff; border: none; outline: none; box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 6px, rgba(0, 0, 0, 0.12) 0px 1px 4px; border-radius: 2px; cursor: pointer; border-radius: 4px;">确定</button>
        </div>
      </div>
    `
    alertEle.innerHTML = alertStr
    document.body.appendChild(alertEle)
  }
  function resetTask(e) {
    e.stopPropagation()
    if(e.type === 'contextmenu') {
        e.returnValue=false
    }
    if((e.type === 'click' || e.type === 'touchend') && e.target.id==='_alert_id_' + hash){
        clearEvent()
        closeCallback && closeCallback()
    }
  }
  function clearEvent() {
    document.removeEventListener('click', resetTask, false)
    document.removeEventListener('touchend', resetTask, false)
    document.body.removeChild(alertEle)
  }

  return {
    close: cb => {
      cb && (closeCallback = cb)
    }
  }
}

// 带有取消按钮的弹框
export const s_alert = (msg, href, type='student') => {

  let alertEle = null
  let closeCallback
  const hash = new Date().getTime()

  init()

  function init() {
    createalertEle()
    document.addEventListener('click', resetTask, false)
    document.addEventListener('touchend', resetTask, false)
  }
  function createalertEle() {
    alertEle = document.createElement('div')
    alertEle.style.width = window.innerWidth + 'px'
    alertEle.style.height = window.innerHeight + 'px'
    alertEle.style.position = 'fixed'
    alertEle.style.left = 0
    alertEle.style.top = 0
    alertEle.style.zIndex = 999999999
    alertEle.style.backgroundColor = 'rgba(0,0,0,0.7)'
    alertEle.style.display = 'block'

    const alertStr = `
      <div style="width: 400px; height: 180px; background: #fff; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); font-size: 16px; border-radius: 5px; overflow: hidden;">
        <p style="width: 100%; height: 40px; line-height: 40px; font-weight: 700; background: #efefef; color: #333; text-indent: 28px; border-bottom: 1px solid #ccd0d6; margin: 0;">${type==='student' ? '提示' : 'Message'}</p>
        <div style="text-align: center;">
          <p style="width: 100%; line-height: 80px; text-align: center; font-weight: 700; margin: 0;">${msg}</p>
          <button id=${'_alert_cancel_id_' + hash} style="width: 100px; height: 30px; line-height: 30px; background: rgb(255, 255, 255); color: #333; border: 1px solid #333; box-sizing: content-box; outline: none; box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 6px, rgba(0, 0, 0, 0.12) 0px 1px 4px; border-radius: 2px; cursor: pointer; border-radius: 4px; margin-right: 30px;">${type==='student' ? '取消' : 'cancel'}</button>
          <a id=${'_alert_id_' + hash} href=${href} target="_blank" style="display: inline-block; width: 120px; height: 34px; line-height: 34px; background: rgb(41, 155, 228); box-sizing: content-box; color: #fff; border: none; outline: none; box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 6px, rgba(0, 0, 0, 0.12) 0px 1px 4px; border-radius: 2px; cursor: pointer; border-radius: 4px;">${type==='student' ? '确定' : 'ok'}</a>
        </div>
      </div>
    `
    alertEle.innerHTML = alertStr
    document.body.appendChild(alertEle)
  }
  function resetTask(e) {
    e.stopPropagation()
    if(e.type === 'contextmenu') {
        e.returnValue=false
    }
    if(e.type === 'click' || e.type === 'touchend'){
      if(e.target.id === '_alert_id_' + hash) {
        var timer = setTimeout(()=>{
          clearEvent()
        }, 400)
      }else if(e.target.id === '_alert_cancel_id_' + hash) {
        clearEvent()
        closeCallback && closeCallback()
      }
    }
  }
  function clearEvent() {
    document.removeEventListener('click', resetTask, false)
    document.removeEventListener('touchend', resetTask, false)
    try{
      document.body.removeChild(alertEle)
    }catch(err){
      console.log(err)
    }
  }

  return {
    close: cb => {
      cb && (closeCallback = cb)
    }
  }
}

// 英文版弹框
export const t_alert = (msg='模拟alert弹框') => {

  let alertEle = null
  let closeCallback
  const hash = new Date().getTime()

  init()

  function init() {
    createalertEle()
    document.addEventListener('click', resetTask, false)
    document.addEventListener('touchend', resetTask, false)
  }
  function createalertEle() {
    alertEle = document.createElement('div')
    alertEle.style.width = window.innerWidth + 'px'
    alertEle.style.height = window.innerHeight + 'px'
    alertEle.style.position = 'fixed'
    alertEle.style.left = 0
    alertEle.style.top = 0
    alertEle.style.zIndex = 999999999
    alertEle.style.backgroundColor = 'rgba(0,0,0,0.7)'
    alertEle.style.display = 'block'

    const alertStr = `
      <div style="width: 400px; height: 180px; background: #fff; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); font-size: 16px; border-radius: 5px; overflow: hidden;">
        <p style="width: 100%; height: 40px; line-height: 40px; font-weight: 700; background: #efefef; color: #333; text-indent: 28px; border-bottom: 1px solid #ccd0d6; margin: 0;">Message</p>
        <div style="text-align: center;">
          <p style="width: 100%; height: 90px; line-height: 30px; padding: 20px; box-sizing: border-box; text-align: center; font-weight: 350; margin: 0;">${msg}</p>
          <button id=${'_alert_id_' + hash} style="width: 120px; height: 34px; line-height: 34px; background: rgb(41, 155, 228); color: #fff; border: none; outline: none; box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 6px, rgba(0, 0, 0, 0.12) 0px 1px 4px; border-radius: 2px; cursor: pointer; border-radius: 4px;">Ok</button>
        </div>
      </div>
    `
    alertEle.innerHTML = alertStr
    document.body.appendChild(alertEle)
  }
  function resetTask(e) {
    e.stopPropagation()
    if(e.type === 'contextmenu') {
        e.returnValue=false
    }
    if((e.type === 'click' || e.type === 'touchend') && e.target.id==='_alert_id_' + hash){
        clearEvent()
        closeCallback && closeCallback()
    }
  }
  function clearEvent() {
    document.removeEventListener('click', resetTask, false)
    document.removeEventListener('touchend', resetTask, false)
    document.body.removeChild(alertEle)
  }

  return {
    close: cb => {
      cb && (closeCallback = cb)
    }
  }
}

export const teacherTransformErr = (err={}) => {
  let errMessage = ''
  const code = err.code
  switch(code) {
    case 6:
      errMessage = 'Verification code error!'
      break;
    case 7:
      errMessage = 'Wrong email or password!'
      break;
    default:
      errMessage = err.msg
  }
  return errMessage
}

export const studentTransformErr = (err={}) => {
  let errMessage = ''
  const code = err.code || 0
  switch(code) {
    case 6:
      errMessage = '验证码错误！'
      break;
    case 7:
      errMessage = '手机号或密码错误！'
      break;
    default:
      errMessage = err.msg
  }
  return errMessage
}

export const bodyScrollTop = (number = 0, time) => {
  if (!time) {
      document.body.scrollTop = document.documentElement.scrollTop = number;
      return number;
  }
  const spacingTime = 20; // 设置循环的间隔时间  值越小消耗性能越高
  let spacingInex = time / spacingTime; // 计算循环的次数
  let nowTop = document.body.scrollTop + document.documentElement.scrollTop; // 获取当前滚动条位置
  let everTop = (number - nowTop) / spacingInex; // 计算每次滑动的距离
  let scrollTimer = setInterval(() => {
      if (spacingInex > 0) {
          spacingInex--;
          bodyScrollTop(nowTop += everTop);
      } else {
          clearInterval(scrollTimer); // 清除计时器
      }
  }, spacingTime);
};

export const getPlatformType = () => {
  const userAgent = navigator.userAgent
  const isPad = /pad/i.test(userAgent)
  return isPad
}